define(["require", "exports", "./childrenBuilder", "./util"], function (require, exports, childrenBuilder_1, util_1) {
    "use strict";
    exports.__esModule = true;
    exports.ifChildren = void 0;
    /**
     * 子元素集片段是动态生成的，watchAfter后直接新入
     * @param fun
     */
    function ifChildren(fun) {
        return function (parent, me) {
            var currentInit;
            var currentDestroy;
            var virtualChild;
            var currentLifeModel;
            var life = (0, util_1.onceLife)(function () {
                currentDestroy = (0, util_1.orRun)(currentInit);
                return function () {
                    w.disable();
                    currentLifeModel.destroy();
                    (0, util_1.orRun)(currentDestroy);
                };
            });
            var w = util_1.Watcher.ofExp(function () {
                if (currentLifeModel) {
                    currentLifeModel.destroy();
                }
                currentLifeModel = (0, util_1.newLifeModel)();
            }, function () {
                return fun(currentLifeModel.me);
            }, function (children) {
                if (currentDestroy) {
                    if (life.isInit) {
                        currentDestroy();
                    }
                    currentDestroy = null;
                }
                currentInit = null;
                if (virtualChild) {
                    parent.remove(0);
                    virtualChild = null;
                }
                if (children) {
                    //初始化
                    virtualChild = parent.newChildAtLast();
                    currentInit = (0, childrenBuilder_1.baseChildrenBuilder)(currentLifeModel.me, children, virtualChild);
                    if (life.isInit) {
                        currentDestroy = (0, util_1.orRun)(currentInit);
                    }
                }
            });
            return life.init;
        };
    }
    exports.ifChildren = ifChildren;
});
